package com.ruoyi.user.controller.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SpffNotifications;
import com.ruoyi.system.service.ISpffNotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通知Controller
 * 
 * @author xjj
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/userApi/notifications")
public class USpffNotificationsController extends BaseController
{
    @Autowired
    private ISpffNotificationsService spffNotificationsService;

    /**
     * 查询通知列表（用户端，无需权限验证）
     * @param typeStr 通知类型字符串：interaction-互动，system-系统，不传或all则查询全部
     */
    @GetMapping("/list")
    public TableDataInfo list(SpffNotifications spffNotifications, String type)
    {
        try {
            // 获取当前登录用户ID，只查询自己的通知
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            spffNotifications.setUserId(userId);
            
            // 处理type参数：将字符串类型转换为数字类型
            // 注意：对于'interaction'类型，包含多个类型值，需要特殊处理
            if (type != null && !type.isEmpty() && !"all".equals(type)) {
                if ("system".equals(type)) {
                    spffNotifications.setType(5); // 系统通知
                } else if ("interaction".equals(type)) {
                    // 互动类型包括：1-点赞, 2-评论, 3-关注, 4-收藏
                    // 对于这种情况，我们需要使用特殊的查询方法
                    startPage();
                    List<SpffNotifications> list = spffNotificationsService.selectInteractionNotificationsList(userId);
                    return getDataTable(list);
                } else {
                    // 尝试将字符串转换为数字
                    try {
                        spffNotifications.setType(Integer.parseInt(type));
                    } catch (NumberFormatException e) {
                        // 如果转换失败，忽略type参数
                    }
                }
            }
            
            startPage();
            List<SpffNotifications> list = spffNotificationsService.selectSpffNotificationsList(spffNotifications);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("获取通知列表失败：" + e.getMessage());
            return getDataTable(new java.util.ArrayList<>());
        }
    }

    /**
     * 获取通知详细信息（用户端）
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        try {
            SpffNotifications notification = spffNotificationsService.selectSpffNotificationsById(id);
            
            // 验证通知是否属于当前用户
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            if (notification != null && notification.getUserId().equals(userId)) {
                return success(notification);
            } else {
                return error("无权访问此通知");
            }
        } catch (Exception e) {
            return error("获取通知详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增通知
     */
    @Log(title = "通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpffNotifications spffNotifications)
    {
        return toAjax(spffNotificationsService.insertSpffNotifications(spffNotifications));
    }

    /**
     * 修改通知
     */
    @Log(title = "通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpffNotifications spffNotifications)
    {
        return toAjax(spffNotificationsService.updateSpffNotifications(spffNotifications));
    }

    /**
     * 删除通知（用户端，只能删除自己的）
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            
            // 验证所有通知都属于当前用户
            for (Long id : ids) {
                SpffNotifications notification = spffNotificationsService.selectSpffNotificationsById(id);
                if (notification == null || !notification.getUserId().equals(userId)) {
                    return error("无权删除此通知");
                }
            }
            
            return toAjax(spffNotificationsService.deleteSpffNotificationsByIds(ids));
        } catch (Exception e) {
            return error("删除通知失败：" + e.getMessage());
        }
    }

    /**
     * 获取未读通知数量
     * @param type 通知类型（可选）：interaction-互动，system-系统，不传则返回总数
     */
    @GetMapping("/unread-count")
    public AjaxResult getUnreadCount(String type)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            Integer typeValue = null;
            
            // 转换type字符串为数字
            if (type != null && !type.isEmpty()) {
                switch (type) {
                    case "like":
                        typeValue = 1;
                        break;
                    case "comment":
                        typeValue = 2;
                        break;
                    case "follow":
                        typeValue = 3;
                        break;
                    case "collect":
                        typeValue = 4;
                        break;
                    case "system":
                        typeValue = 5;
                        break;
                    case "interaction":
                        // 互动类型包括：点赞、评论、关注、收藏
                        int likeCount = spffNotificationsService.selectSpffNotificationsUnreadCountByType(userId, 1);
                        int commentCount = spffNotificationsService.selectSpffNotificationsUnreadCountByType(userId, 2);
                        int followCount = spffNotificationsService.selectSpffNotificationsUnreadCountByType(userId, 3);
                        int collectCount = spffNotificationsService.selectSpffNotificationsUnreadCountByType(userId, 4);
                        int totalInteraction = likeCount + commentCount + followCount + collectCount;
                        return success(totalInteraction);
                }
            }
            
            // 如果指定了具体类型，按类型查询
            if (typeValue != null) {
                int num = spffNotificationsService.selectSpffNotificationsUnreadCountByType(userId, typeValue);
                return success(num);
            }
            
            // 未指定类型，返回总数
            SpffNotifications query = new SpffNotifications();
            query.setUserId(userId);
            query.setIsRead(0); // 0-未读
            
            int num = spffNotificationsService.selectSpffNotificationsUnreadCount(query);
            return success(num);
        } catch (Exception e) {
            return error("获取未读数量失败：" + e.getMessage());
        }
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/mark-read")
    public AjaxResult markAsRead(@RequestBody Map<String, Object> params)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            Object idsObj = params.get("ids");

            if (idsObj == null) {
                // 标记所有未读通知为已读
                return toAjax(spffNotificationsService.markAllAsReadByUserId(userId));
            } else {
                // 安全地处理ID列表，兼容Integer和Long类型
                List<?> rawIds = (List<?>) idsObj;
                List<Long> ids = new ArrayList<>();

                for (Object obj : rawIds) {
                    if (obj instanceof Integer) {
                        ids.add(((Integer) obj).longValue());
                    } else if (obj instanceof Long) {
                        ids.add((Long) obj);
                    }
                }

                // 验证通知属于当前用户
                for (Long id : ids) {
                    SpffNotifications notification = spffNotificationsService.selectSpffNotificationsById(id);
                    if (notification == null || !notification.getUserId().equals(userId)) {
                        return error("无权操作此通知");
                    }
                }

                return toAjax(spffNotificationsService.markAsReadByIds(ids.toArray(new Long[0])));
            }
        } catch (Exception e) {
            return error("标记已读失败：" + e.getMessage());
        }
    }
}
